package org.elec.mac.ws;


import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.elec.mac.ehcache.CacheConfiguration;
import org.json.JSONObject;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;

/**
 * Created by Bean on 2017/10/13.
 */
@Slf4j
public class WebSocketHandler implements org.springframework.web.socket.WebSocketHandler {

    @Setter
    private static CacheConfiguration cacheConfiguration;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        EhCacheCacheManager cacheCacheManager = cacheConfiguration.ehCacheCacheManager(cacheConfiguration.ehCacheManagerFactoryBean());
        Cache wsCache = cacheCacheManager.getCache("webSocketCache");
        Map<String, Object> map = session.getAttributes();
        String machid = (String) map.get("machid");
        log.info(machid);
        wsCache.put(machid, session);
        log.info("afterConnectionEstablished");
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        log.info("handleMessage");
        log.info(message.getPayload().toString());
        EhCacheCacheManager cacheCacheManager = cacheConfiguration.ehCacheCacheManager(cacheConfiguration.ehCacheManagerFactoryBean());
        Cache wsCache = cacheCacheManager.getCache("webSocketCache");
        Map<String, Object> map = session.getAttributes();
        String machid = (String) map.get("machid");

        JSONObject jsonObject = new JSONObject(message.getPayload().toString());
        WebSocketSession socketSession = wsCache.get(machid, WebSocketSession.class);
        String state = jsonObject.getString("state");
        if("SUCCESS".equals(state)) {
            try {
                socketSession.close();
            }
            catch (IOException ex) {
                log.error("SocketSession Close : ", ex);
            }
            finally {
                wsCache.evict(machid);
            }
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info("handleTransportError");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        log.info("afterConnectionClosed");
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    public String randomNum(int num){
        return RandomStringUtils.randomAlphanumeric(num);
    }
}
